package cn.andy.android.crm.fragment;

import cn.andy.android.crm.R;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MapDemoFragment extends Fragment implements LocationListener {
	private final static String TAG = "MapDemoFragment";
	private LocationManager lm;

	private TextView tvlocation;
	private Button btnlocate;
	private View view;
	
	private String[] location = {"39.993325568745725,116.3037652029633", //北京大学
								 "31.24169,121.49491", //东方明珠
								 "25.041006,121.521381", //台湾大学
								 "30.25287,120.13646", //西湖
								 "", //钓鱼岛
								 "", //
								 ""};

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		view = inflater.inflate(R.layout.fragment_mapdemo, container, false);

		// 与Location_service建立连接
		lm = (LocationManager) getActivity().getSystemService(
				Context.LOCATION_SERVICE);
		// 注册activity到监听队列中
		lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1l, 1l, this);
		// lm.getProvider(LocationManager.GPS_PROVIDER).requiresNetwork();
		Log.d(TAG, "got location");

		tvlocation = (TextView) view.findViewById(R.id.mapdemo_location);
		btnlocate = (Button) view.findViewById(R.id.btnlocate);

		setNewInfo();

		btnlocate.setOnClickListener(new Button.OnClickListener() {

			public void onClick(View arg0) {
				setNewInfo();
				new AlertDialog.Builder(getActivity()).setTitle("Select").
				setItems(R.array.labels, new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						if(which > 0){
							String loc = location[which - 1];
							Uri uri = Uri.parse("geo:"+loc);//http://ditu.google.cn/maps?hl=zh&mrt=loc&q=
							Intent intent = new Intent(Intent.ACTION_VIEW, uri);
							intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK & Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
							startActivity(intent);
						} else {
							Criteria criteria = new Criteria();  
							criteria.setAccuracy(Criteria.ACCURACY_FINE);  
							String provider = lm.getBestProvider(criteria, true);  
							Location loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
							int count = 0;
							while (loc == null) {
								lm.requestLocationUpdates(provider, 2000, 0, MapDemoFragment.this);
								loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
								count ++;
							}

							if (loc != null) {
								Uri uri = Uri.parse("geo:" + loc.getLatitude() + ","
										+ loc.getLongitude());
								Intent intent = new Intent(Intent.ACTION_VIEW, uri);
								startActivity(intent);
							} else {
								Toast.makeText(getActivity(), R.string.tab_mapdemo_canntlocate, Toast.LENGTH_SHORT).show();
							}
						}
					}
				}).create().show();

			}
		});

		return view;
	}
	
	@Override
	public void onResume() {
		super.onResume();
	}
	
	@Override
	public void onPause() {
		super.onPause();
	}

	// Location发生变化时会调用这个
	public void onLocationChanged(Location location) {
		Log.d(TAG, "location: " + location);
		setNewInfo();
	}

	// 关闭GPS卫星会调用这个
	public void onProviderDisabled(String provider) {
		Log.d(TAG, "provider disable" + provider);
		setNewInfo();
	}

	// 启用GPS卫星会调用这个
	public void onProviderEnabled(String provider) {
		Log.d(TAG, "provider enable");
		setNewInfo();
	}

	public void onStatusChanged(String provider, int status, Bundle extras) {
		Log.d(TAG, "status changed status = " + status);
	}

	private void setNewInfo() {
		boolean isopengps = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
		if (!isopengps) {
			new AlertDialog.Builder(getActivity())
			.setTitle(R.string.message_map_enablelocation)
			.setNegativeButton(R.string.message_map_no,
					new DialogInterface.OnClickListener() {

				public void onClick(DialogInterface dialog,
						int which) {
					dialog.cancel();
				}
			})
			.setPositiveButton(R.string.message_map_yes,
					new DialogInterface.OnClickListener() {

				public void onClick(DialogInterface dialog,
						int which) {
					startActivity(new Intent(
							Settings.ACTION_LOCATION_SOURCE_SETTINGS));
				}
			}).create().show();
		}
		
		Criteria criteria = new Criteria();  
		criteria.setAccuracy(Criteria.ACCURACY_FINE);  
		String provider = lm.getBestProvider(criteria, true);  
		Location loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
		int count = 0;
		while (loc == null && count < 200) {
			lm.requestLocationUpdates(provider, 2000, 0, MapDemoFragment.this);
			loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
			count ++;
		}
		
		if (loc != null)
			tvlocation.setText("經度：" + loc.getLongitude() + "\n緯度："
					+ loc.getLatitude() + "\n速度：" + loc.getSpeed() + "\n時間："
					+ loc.getTime());
	}

}
